<template>
	<!--邀请卡-->
	<z-paging>
		<view class="yaoqingka-view">
			<view class="header_box">
				<u-sticky>
					<hedsty :headCentext="'邀请海报'"></hedsty>
				</u-sticky>
			</view>
			<!-- 海报 -->
			<view class="img_view_box">
				<image v-if="resultSrc" :src="resultSrc" mode="scaleToFill" @longpress="save" />
			</view>
			<!--底部选项卡-->
			<view class="bottom-view-box">

				<scroll-view class="list-view" scroll-x>
					<view class="borderBox list" v-for="(item, i) in cardList" :key='i'
						:class="chooseIndex == i ? 'active' : ''" @click.stop="chooseHaibao(i)">
						<image :src="item.img" mode="aspectFill" show-menu-by-longpress />
					</view>
				</scroll-view>
				<view class="invite_zs_box" @click="invitSubmit">
					保存/分享海报
				</view>
			</view>
			<view style="position: fixed;top: -9999999px;">
				<canvas id="my-canvas" type="2d" class="my-canvas" />
			</view>
			<!-- 分享示例 -->
			<!-- <u-popup :show="shareShow" mode="bottom" bgColor="#040616">
			<view class="share_big_box">
				<view class="share_btn_box">
					<view class="dange_box_s" v-for="(item, index) in caozuoList" :key="index" @click="handle(item)">
						<view class="top_image_box">
							<image :src="item.icon" />
						</view>
						<view class="text_xiazai_box">{{ item.txt }}</view>
					</view>
				</view>
				<view class="invite_zs_box" @click="shareclose">
					取消分享
				</view>
			</view>
		</u-popup> -->
		</view>
	</z-paging>
</template>

<script>
	import hedsty from '../../components/hedsty.vue'
	import {
		downloaImage
	} from '@/utils/request.js';
	let ctx;
	let canvas;
	let timer;
	export default {
		components: {
			hedsty
		},
		data() {
			return {
				brand: '摩根潮玩',
				// 用户数据
				userInfo: {
					nickName: '',
					avatarUrl: ''
				},
				qrcode: '', //太阳码
				chooseIndex: 0, //选择序列号
				cardList: [{

				}], // 海报列表
				drawList: [], // 需要画在画布上的元素
				resultSrc: '', // 最后生成的图片
				shareShow: false, //分享类型弹窗
				caozuoList: [{
						id: 1,
						icon: 'https://yq.dingxians.cn/upload/static/invited/xiazai.png',
						txt: '保存到相册'
					},
					{
						id: 2,
						icon: 'https://yq.dingxians.cn/upload/static/invited/weixin.png',
						txt: '转发给好友'
					},
					{
						id: 3,
						icon: 'https://yq.dingxians.cn/upload/static/invited/pengyouquan.png',
						txt: '分享朋友圈'
					}
				],
				shsareImages: []
			}
		},
		onUnload() {

			if (timer) {
				clearInterval(timer);
				timer = null;
			}
		},
		onLoad(e) {
			console.log(e)

			// this.qrcode = 'https://yq.dingxians.cn/upload/static/poster1.jpg'
			// const query = uni.createSelectorQuery()
			// query.select('#my-canvas')
			// 	.fields({
			// 		node: true,
			// 		size: true
			// 	})
			// 	.exec(async (res) => {
			// 		canvas = res[0].node
			// 		ctx = canvas.getContext('2d')
			// 		const dpr = uni.getSystemInfoSync().pixelRatio
			// 		canvas.width = res[0].width * dpr // 获取宽
			// 		canvas.height = res[0].height * dpr // 获取高
			// 		ctx.scale(dpr, dpr)
			// 		ctx.textBaseline = 'top';
			// 		await this.getCardList();
			// 		this.$nextTick(() => {
			// 			this.chooseHaibao(0);
			// 		});
			// 	});
			this.getQrcodeImage()
		},
		methods: {

			// 获取太阳码
			getQrcodeImage() {
				this.$Request.post(this.$api.share.usersGetWxCode).then(res => {
					if (res.code == 200) {
						let imageSrc = res.url
						this.shsareImages = res.img
						this.getTempFilePath(imageSrc)
					}
				})
			},
			// 转码
			getTempFilePath(base64Data) {
				return new Promise((resolve, reject) => {
					const fs = uni.getFileSystemManager()
					base64Data = base64Data.split(',')[1]
					const fileName = 'temp_image_' + Date.now() + '.png' // 自定义文件名，可根据需要修改
					const filePath = uni.env.USER_DATA_PATH + '/' + fileName
					const buffer = uni.base64ToArrayBuffer(base64Data)
					fs.writeFile({
						filePath,
						data: buffer,
						encoding: 'binary',
						success: res => resolve(filePath),
						fail: err => reject(err)
					})


					let userInfo = uni.getStorageSync('userInfo')
					this.userInfo.nickName = userInfo.nickname
					this.userInfo.avatarUrl = userInfo.avatar
					this.qrcode = filePath


					const query = uni.createSelectorQuery()
					query.select('#my-canvas')
						.fields({
							node: true,
							size: true
						})
						.exec(async (res) => {
							canvas = res[0].node
							ctx = canvas.getContext('2d')
							const dpr = uni.getSystemInfoSync().pixelRatio
							canvas.width = res[0].width * dpr // 获取宽
							canvas.height = res[0].height * dpr // 获取高
							ctx.scale(dpr, dpr)
							ctx.textBaseline = 'top';
							await this.getCardList();
							this.$nextTick(() => {
								this.chooseHaibao(0);
							});
						});
					// this.$router('/userPage/invited/poster?imageSrc=' + filePath + '&image=' + JSON.stringify(image))
				});
			},


			// 打开分享操作弹窗
			invitSubmit() {
				// this.shareShow = true
				wx.downloadFile({
					url: this.resultSrc,
					success: (res) => {
						console.log(res)
						wx.showShareImageMenu({
							path: res.tempFilePath
						})
					}
				})
			},
			//关闭分享操作弹窗
			// shareclose() {
			// 	this.shareShow = false
			// },
			// 1保存、2转发、3分享操作
			// handle(item) {

			// 	if (item.id == 1) {
			// 		this.saveImage()
			// 	} else if (item.id == 2) {
			// 		this.shareImage()
			// 	} else {
			// 		this.shareToTimeline()
			// 	}
			// },
			// 转发给好友
			// shareImage() {
			// 	wx.downloadFile({
			// 	   url: this.resultSrc,
			// 	   success: (res) => {
			// 	     wx.showShareImageMenu({
			// 	       path: res.tempFilePath
			// 	     })
			// 	   }
			// 	 })
			// uni.share({
			// 	provider: "weixin",
			// 	scene: "WXSceneSession",
			// 	type: 2,
			// 	imageUrl: this.resultSrc,
			// 	success: function(res) {
			// 		console.log("success:" + JSON.stringify(res));
			// 	},
			// 	fail: function(err) {
			// 		console.log("fail:" + JSON.stringify(err));
			// 	}
			// });
			// },
			// 分享到朋友圈
			// shareToTimeline() {
			// 	let image = this.resultSrc;
			// 	uni.share({
			// 		provider: "weixin",
			// 		scene: "WXSceneSession",
			// 		type: 2,
			// 		imageUrl: image,
			// 		success: function(res) {
			// 			console.log("success:" + JSON.stringify(res));
			// 		},
			// 		fail: function(err) {
			// 			console.log("fail:" + JSON.stringify(err));
			// 		}
			// 	});

			// },

			// 获取海报列表
			getCardList() {
				this.cardList = this.shsareImages

			},

			//选择海报
			async chooseHaibao(index) {
				let self = this;
				//将图片的信息存起来,再进行跳转
				this.chooseIndex = index;
				let item = self.cardList[self.chooseIndex];
				if (item.createImg) { //如果图片已经生成过则直接使用

					var uploadurl = "https://yq.dingxians.cn/api/common/upload?token=" + uni.getStorageSync(
						"token")
					uni.uploadFile({
						url: uploadurl,
						filePath: item.createImg,
						name: 'file',
						// formData: {
						//     'openid': this.openId
						// },
						success: (res) => {
							let urlData = JSON.parse(res.data)
							this.resultSrc = urlData.data.url;
						}
					});


					uni.hideLoading();
					if (timer) {
						clearInterval(timer);
						timer = null;
					};
					return;
				};
				this.drawList = [];
				//下载背景图片
				this.drawList.push({
					zIndex: -100,
					left: 0,
					top: 0,
					scale: 1,
					type: 'img',
					img: await downloaImage(canvas, item.img),
					width: 500,
					height: 800
				});
				// 太阳码
				let qrcdoePng = this.qrcode;
				this.drawList.push({
					zIndex: 1,
					left: 340,
					top: 660,
					scale: 1,
					type: 'img',
					img: await downloaImage(canvas, qrcdoePng),
					width: 132,
					height: 132
				});
				// 用户昵称
				this.drawList.push({
					zIndex: 2,
					left: 145,
					top: 670,
					scale: 1,
					fontSize: 16,
					type: 'text',
					content: this.userInfo.nickName
				});
				// 邀请你
				this.drawList.push({
					zIndex: 2,
					left: 145,
					top: 710,
					scale: 1,
					fontSize: 16,
					type: 'text',
					content: `${this.brand}邀请您`
				});
				// 用户头像
				if (this.userInfo.avatarUrl) {
					this.drawList.push({
						zIndex: 3,
						left: 20,
						top: 660,
						scale: 1,
						type: 'img',
						img: await downloaImage(canvas, this.userInfo.avatarUrl),
						width: 106,
						height: 106
					});
				}
				// console.log(this.drawList, "this.drawList")
				uni.showLoading({
					title: '生成中...'
				});
				startDraw();
				//绘制
				function startDraw() {
					//按z-index排序
					self.drawList = self.drawList.sort((a, b) => {
						return Number(a.zIndex) - Number(b.zIndex);
					});
					self.drawList.forEach((item) => {
						if (item.type == 'text') {
							self.drawText(item);
						} else {
							self.drawImg(item);
						}
					});
					uni.canvasToTempFilePath({
						destWidth: 500,
						destHeight: 800,
						canvas: canvas,
						success: (res) => {
							uni.hideLoading();
							ctx.clearRect(0, 0, 500, 800);
							let tmpPath = res.tempFilePath;
							item.createImg = tmpPath; //给元素赋值，使之第二次不需要再次生成图片
							var uploadurl = "https://yq.dingxians.cn/api/common/upload?token=" +
								uni.getStorageSync("token")
							uni.uploadFile({
								url: uploadurl,
								filePath: item.createImg,
								name: 'file',
								success: (res) => {
									let urlData = JSON.parse(res.data)
									self.resultSrc = urlData.data.url
								}
							});

						},
						fail: (err) => {
							console.log(err, 2222)
						}
					});
				};
			},
			drawText(item) {
				if (item.content) {
					ctx.font = `${Number(item.fontSize) || 16}px 楷体`;
					ctx.fillStyle = item.color || '#333333'; ///颜色
					ctx.fillText(item.content, Number(item.left), Number(item.top));
				};
			},
			//绘制图片
			drawImg(item) {
				//由于缩放是以图片的中心点缩放的，所以会改变图像的left 和top值
				ctx.save();
				let width = Number(item.width); //初始的宽高
				let height = Number(item.height);
				item.top = Number(item.top);
				item.left = Number(item.left);
				item.scale = Number(item.scale);

				if (item.img) {
					ctx.drawImage(item.img, item.left, item.top,
						item.width * item.scale, item.height * item.scale);
				}
				ctx.restore();
			},
			save() {
				uni.saveImageToPhotosAlbum({
					filePath: this.resultSrc,
					success: () => {
						this.showToast('保存成功', 'success');
					}
				})
			},
			showToast(title, icon = 'none') {
				uni.showToast({
					title: title ? title.toString() : '重新登陆',
					icon
				});
			},
			//保存图片
			// saveImage() {
			// 	// 假设已有图片路径

			// 	// 先下载图片到本地
			// 	uni.downloadFile({
			// 		url: this.resultSrc,
			// 		success: downloadResult => {
			// 			if (downloadResult.statusCode === 200) {
			// 				// 获取下载后的图片临时文件路径
			// 				let tempFilePath = downloadResult.tempFilePath;

			// 				// 保存图片到相册
			// 				uni.saveImageToPhotosAlbum({
			// 					filePath: tempFilePath,
			// 					success: () => {
			// 						uni.showToast({
			// 							title: '保存成功'
			// 						});
			// 					},
			// 					fail: () => {
			// 						uni.showToast({
			// 							title: '保存失败',
			// 							icon: 'none'
			// 						});
			// 					}
			// 				});
			// 			}
			// 		},
			// 		fail: (err) => {
			// 			console.log(err, "下载失败")
			// 			uni.showToast({
			// 				title: '下载失败',
			// 				icon: 'none'
			// 			});
			// 		}
			// 	});
			// }
		}
	}
</script>

<style lang="scss" scoped>
	.yaoqingka-view {
		width: 100vw;
		height: 100vh;

		.header_box {
			width: 100%;
			height: 166rpx;
			background-size: 100% 100%;
		}

		.img_view_box {
			width: 100%;
			height: calc(100vh - 466rpx);

			image {
				width: 100%;
				height: 100%;
			}
		}

		.bottom-view-box {
			width: 100%;
			height: 300rpx;
			position: fixed;
			bottom: 0;
			border-top: 1rpx solid rgba(231, 231, 231, .3);



			scroll-view {
				height: 130rpx;
				white-space: nowrap;
				// background-color: #fff;

				.list {
					width: 25%;
					display: inline-block;
					height: 100%;
					text-align: center;

					&.active {
						image {
							box-shadow: 0 0 20upx #3eca83;
						}
					}

					image {
						width: 100rpx;
						height: 100rpx;
						border-radius: 10upx;
						margin-top: 30rpx;
					}
				}
			}

			.invite_zs_box {
				width: 654rpx;
				height: 100rpx;
				background: rgba(239, 31, 31, 1);
				border-radius: 50rpx;
				text-align: center;
				line-height: 100rpx;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #FFFFFF;
				margin: 50rpx auto;
			}
		}

		.my-canvas {
			width: 500px;
			height: 800px;
		}

		.share_big_box {
			width: 750rpx;
			height: 300rpx;
			border-top-left-radius: 30rpx;
			border-top-right-radius: 30rpx;

			.share_btn_box {
				width: 100%;
				height: 160rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.dange_box_s {
					width: 33%;
					height: 100%;

					.top_image_box {
						width: 80rpx;
						height: 80rpx;
						margin: 20rpx auto;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.text_xiazai_box {
						width: 100%;
						height: 27rpx;
						font-family: PingFang SC;
						font-weight: bold;
						font-size: 28rpx;
						color: rgba(175, 175, 175, 1);
						line-height: 27rpx;
						text-align: center;
					}
				}

			}

			.invite_zs_box {
				width: 654rpx;
				height: 100rpx;
				background: linear-gradient(262deg, #7AD8FA, #432FFF);
				border-radius: 50rpx;
				text-align: center;
				line-height: 100rpx;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 36rpx;
				color: #FFFFFF;
				margin: 10rpx auto;
			}
		}
	}
</style>